const Category = require('../models/Category');

// 获取所有分类（支持分页和条件查询）
const getAllCategoriesService = async (params) => {
    try {
        const where = {};
        let page = 1;
        let pageSize = 10;

        if (params) {
            if (params.name) {
                where.name = params.name;
            }
            if (params.status !== undefined) {
                where.status = params.status;
            }
            if (params.parent_id !== undefined) {
                where.parent_id = params.parent_id;
            }
            if (params.page) {
                page = parseInt(params.page, 10);
            }
            if (params.pageSize) {
                pageSize = parseInt(params.pageSize, 10);
            }
        }

        const offset = (page - 1) * pageSize;
        const limit = pageSize;

        const { count, rows } = await Category.findAndCountAll({
            where: where,
            attributes: [
                'id',
                'name',
                'parent_id',
                'sort',
                'status',
                'created_at',
                'updated_at'
            ],
            offset: offset,
            limit: limit,
            order: [['sort', 'ASC'], ['id', 'DESC']]
        });

        return {
            total: count,
            list: rows,
            page: page,
            pageSize: pageSize
        };
    } catch (err) {
        throw new Error(`Error in getAllCategoriesService: ${err.message}`);
    }
};

// 根据 ID 查询单个分类信息
const getCategoryById = async (categoryId) => {
    try {
        const category = await Category.findByPk(categoryId, {
            attributes: [
                'id',
                'name',
                'description',
                'image_url',
                'status',
                'sort_order',
                'created_at',
                'updated_at'
            ],
        });
        if (!category) {
            throw new Error('Category not found');
        }
        return category;
    } catch (err) {
        throw err;
    }
};

// 新增分类
const addCategory = async (categoryData) => {
    try {
        // 确保必填字段存在
        if (!categoryData.name) {
            throw new Error('Category name is required');
        }
        
        const newCategory = await Category.create({
            name: categoryData.name,
            parent_id: categoryData.parent_id || 0,
            sort: categoryData.sort || 0,
            status: categoryData.status === undefined ? 1 : categoryData.status
        });
        return newCategory;
    } catch (err) {
        throw new Error(`Error in addCategory: ${err.message}`);
    }
};

// 更新分类信息
const updateCategory = async (categoryId, categoryData) => {
    try {
        const existingCategory = await Category.findByPk(categoryId);
        if (!existingCategory) {
            throw new Error('Category not found');
        }
        await existingCategory.update(categoryData);
        return existingCategory;
    } catch (err) {
        throw new Error(`Error in updateCategory: ${err.message}`);
    }
};

// 删除分类
const deleteCategoryService = async (categoryId) => {
    try {
        const existingCategory = await Category.findByPk(categoryId);
        if (!existingCategory) {
            throw new Error('Category not found');
        }
        await existingCategory.destroy();
        return true;
    } catch (err) {
        throw new Error(`Error in deleteCategory: ${err.message}`);
    }
};

module.exports = {
    getAllCategoriesService,
    getCategoryById,
    addCategory,
    updateCategory,
    deleteCategoryService
};
